/**
 * 路由处理方法
 */
// 引入路径处理模块
const path = require('path')
// 生成token
const jwt = require('jsonwebtoken')
// token秘钥
const { secretExpiresIn } = require('../config/tokenSecret')
// 获取数据库数据的方法
const reqSqlData = require('../db/handler_sql');
// 发送邮箱验证码
const nodeMail =require('../config/nodemailer');


// 用户注册接口
function registered(req, res) {
  // 定义sql语句
  let sqlStr = `select * from ev_users where username=?`; // 查询数据
  // let sqlStr = `update ev_users set ? where id = ?`; // 更新数据
  reqSqlData(sqlStr, req.body.username).then(result => {
    if (result?.length == 1) {
      return Promise.reject('用户名已存在，请更换');
    } else {
      let sqlStr1 = `insert into ev_users set ?`; // 插入数据
      req.body.createtime = Date.now()
      return reqSqlData(sqlStr1, [req.body])
    }
  }).then(resultz => {
    res.cc(1, '用户注册成功', {
      status: resultz
    });
    return
  }).catch(err => {
    res.cc(0, err.message || '注册失败')
    return
  })
}
// 用户登录接口
function login(req, res) {
  let sqlStr = `select * from ev_users where username=? and password=?`
  reqSqlData(sqlStr, [req.body.username, req.body.password]).then(result => {
    if (result?.length == 1) {
      // 生成token
      let token = 'Bearer ' + jwt.sign({ ...result[0], password: '',user_pic:'' }, secretExpiresIn.secret, { expiresIn: secretExpiresIn.expiresIn })
      return res.cc(1, '登录成功', { result, token })
    } else {
      return res.cc(0, '登录失败，账号或密码错误')
    }
  }).catch(err => {
    console.log(err)
    return res.cc(0, err.message)
  })
}
// 发送邮箱验证码
function getCode(req, res) {
  const email = req.body.email
  const code = String(Math.floor(Math.random() * 1000000)).padEnd(6, '0') //生成6位随机验证码
  // 处理附件信息
  const Fullpath = path.join(__dirname,'userInfo.js') // 文件路径
  const Filename = path.basename(Fullpath) // 文件全名
  const Cid = path.basename(Fullpath,'.js') // 文件名
  let img = 'https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0e8f5b1dd3ac413d9115caa524b38614~tplv-k3u1fbpfcp-zoom-in-crop-mark:1304:0:0:0.awebp'
  //发送邮件
  const mail = {
    from: `2426594741@qq.com`,// 发件人
    subject: '验证码',//邮箱主题
    to: email,//收件人，这里由post请求传递过来（想给多个人发送，邮箱账号用  ,  隔开）
    // 邮件内容，用html格式编写
    html: `
      <p>您好！</p>
      <p>您的验证码是：<strong style="color:orangered;">${code}</strong></p>
      <p>如果不是您本人操作，请无视此邮件</p>
    `,
    // <image src="${img}"/>
    // 要附带的文件以对象形式写在attachments中
    // attachments: [{
    //   filename: Filename, 
    //   path: Fullpath, 
    //   cid: Cid
    // },{ 
    //   filename: 'app.js', 
    //   path: path.join(__dirname,'../','app.js'), 
    //   cid: 'app'
    // }]
  };
  // console.log(mail.attachments)
  nodeMail.sendMail(mail, (err, info) => {
    if (!err) {
      return res.cc(1,'验证码发送成功',{code,info})
    } else {
      return res.cc(0,'验证码发送失败，请稍后重试',{err:err.message})
    }
  })
}

// 获取验证码登录数据
function  getCodeLogin(req,res){
  let sqlStr = `select * from ev_users where email=?`
  reqSqlData(sqlStr,req.body.email).then(result=>{
    if(result?.length==1){
      let token = 'Bearer ' + jwt.sign({ ...result[0], password: '' }, secretExpiresIn.secret, { expiresIn: secretExpiresIn.expiresIn })
      return res.cc(1,'验证码登录成功',{result,token})
    }
  }).catch(err=>{
    console.log(err)
    return res.cc(0,'验证码登录失败')
  })
}

module.exports = {
  registered,
  login,
  getCode,
  getCodeLogin
}